// pages/PurchaseInformation/PurchaseInformation.js
//var util = require('../../utils/util.js');
let sellerID=''
let userID=''
let goodName=''
let goodPrice=''
let sellerNAME=''
let goodimg=''
let goodID = ''
let date =''
let money = 0
let db =  wx.cloud.database()
let orderNum = 0
let NotNUM = 0
let SellNUM = 0
let distribution = '' //配送方式
let add = ''
let unit = ''  //单位
let inventory = '' //库存
let buynum = 1
let paynum = 0
var UserADD = []
let sellerphone 
Page({
  data: {
    goodName:null,
    goodPrice:null,
    sellerNAME:null,
    goodimg:null,
    Date:null,
    distribution:null,
    add:null,
    unit:null,
    inventory:null,
    buynum:1,
    list:[],
    show: false,
    ADD:[],
    show2:false
  },
  onLoad(options) {
    console.log('订单页面携带的信息：',options)
    sellerID=options.sellerID
    userID=options.userID
    goodID = options.goodID
    this.getMyAddress()
    if(sellerID==userID){
      wx.navigateBack({
        delta: 1
      })
      wx.showToast({
        title: '不可购买',
      })
    }
    goodName=options.goodName
    goodPrice=options.goodPrice
    sellerNAME=options.sellerNAME
    goodimg=options.goodimg
    distribution = options.distribution
    add = options.add
    unit = options.unit
    inventory= options.inventory
    sellerphone = options.phone
    money = goodPrice*100
    var myDate = new Date();
    var mytime=myDate.toLocaleTimeString();
    date=(myDate.getFullYear()+'年'+(myDate.getMonth()+1)+'月'+myDate.getDate()+'日'+mytime)
    this.setDATA()
  },
  // 选择地址
  selectAddress(e){
    console.log('选择的地址：',e.currentTarget.dataset.add)
    var N = e.currentTarget.dataset.add
    UserADD = e.currentTarget.dataset.add
    if(this.data.show2==false){
      this.setData({
        show2:true,
        ADD:N,
      })
    }else{
      this.setData({
        show2:false,
        ADD:N,
        show:true
      })
    }

    console.log(e)
  },
  show() {
    this.setData({
      show: !this.data.show,
      show2:false
    })
  },
  goadd(){
    wx.navigateTo({
      url: '/pages/User-MyAddress/User-MyAddress',
    })
  },
  getMyAddress(){
    wx.cloud.database().collection('User-Address')
    .where({
     _openid:userID
    })
    .get()
    .then(res=>{
      console.log(res)
     this.setData({
       list:res.data
     })
     if(res.data.length==0){
      this.setData({
        show3:true
      })
     }
    })
  },
  setDATA(){
    this.setData({
      goodName:goodName,
      goodPrice:goodPrice,
      sellerNAME:sellerNAME,
      goodimg:goodimg,
      Date:date,
      distribution:distribution,
      add:add,
      unit:unit,
      inventory:inventory
    })
  },
  jia(e){
    console.log(e.currentTarget.dataset.ty)
    if(e.currentTarget.dataset.ty==1){
    //  增加
    if(buynum<inventory){
      console.log('增加')
      buynum=buynum+1
      this.setData({
       buynum:buynum
      })
    }else{
      wx.showToast({
        title: '购买数量不能大于库存',
        icon:'none'
      })
    }
    }else if(e.currentTarget.dataset.ty==2){
      if(buynum>1){
        console.log('减少')
        buynum=buynum-1
        this.setData({
         buynum:buynum
        })
      }
    }
  },
  submitpay() {
    let that = this;
    if(that.data.show2==true){
      money=money*buynum
      paynum = money/100
      wx.cloud.callFunction({
          name: "pay",
          data: {
              money:money
          },
          success(res) {
              console.log("提交成功", res.result)
              that.pay(res.result)
          },
          fail(res) {
              console.log("提交失败", res)
          }
      })
    }else{
     wx.showToast({
       title: '请先选择地址',
       icon:'none'
     })
    }
},
pay(payData) {
  //官方标准的支付方法
  let that = this
  wx.requestPayment({
      timeStamp: payData.timeStamp,
      nonceStr: payData.nonceStr,
      package: payData.package, //统一下单接口返回的 prepay_id 格式如：prepay_id=***
      signType: 'MD5',
      paySign: payData.paySign, //签名
      success(res) {
          console.log("支付成功", res)
          that.goOrderInformation()
      },
      fail(res) {
          console.log("支付失败", res)
      },
      complete(res) {
          console.log("支付完成", res)
      }
  })
},
back(){
  wx.navigateBack({
    delta: 1
  })
},
goOrderInformation(){
  orderNum = Math.floor(Math.random() * 1000) + new Date().getTime() + Math.floor(Math.random() * 1000)
 let state = '待交易'
 wx.cloud.database().collection('Order-information').add({
   data:{
    orderNum:orderNum,
    sellerID:sellerID,
    userID:userID,
    goodName:goodName,
    goodPrice:goodPrice,
    sellerNAME:sellerNAME,
    sellerPhone:sellerphone,
    goodimg:goodimg,
    goodID:goodID,
    date:date,
    state:state,
    distribution:distribution,
    add:add,
    unit:unit,
    buynum:buynum,
    paynum:paynum,
    UserADD:UserADD
   }
})
 .then(res=>{
   console.log('订单信息添加成功：',res)
     this.addAllOrder(1,userID)
     this.addAllOrder(2,sellerID)
     wx.showToast({
      title: '下单成功',
    })
 })
 .catch(err=>{
  console.log('订单信息添加失败：',err)
})
  // wx.navigateTo({
  //   // url: '/pages//UserOrder/UserOrder'
  //   url: '/pages/OrderInformation/OrderInformation?orderNum='+orderNum
  // })
  wx.switchTab({
    url: '/pages/user/user',
  })
},
addAllOrder(type,op){
  let dbcw = db.collection('All-Orders').where({openid:op})
  dbcw.get()
  .then(res=>{
    console.log('NotNum：',NotNUM)
    NotNUM = res.data[0].Not.NotNum
    SellNUM = res.data[0].Sell.SellNum
    console.log('用户订单信息渲染成功：',res)
    console.log('NotNum获取：',NotNUM)
    if(type==1){
      wx.cloud.callFunction({
        name:'changeOrder',
        data:{
         type:type,
         Num:NotNUM,
         orderNum:orderNum,
         openid:userID,
        }
      })
      .then(res=>{
        console.log('购买者订单信息添加成功：',res)
      })
      .catch(err=>{
       console.log('购买者订单信息添加失败：',err)
     })
     } else {
      wx.cloud.callFunction({
        name:'changeOrder',
        data:{
         type:type,
         Num:SellNUM,
         orderNum:orderNum,
         openid:sellerID
        }
      })
      .then(res=>{
        console.log('商家订单信息添加成功：',res)
      })
      .catch(err=>{
       console.log('商家订单信息添加失败：',err)
     })
     }
  })
  .catch(err=>{
    console.log('用户订单信息渲染失败：',err)
  })
}
})